package com.grammer.thread;

/**
 * @author jack
 */
public class MainSubThread {
    public static void main(String[] args) {
        new MainSubThread().init();
    }

    public void init() {
        final Business business = new Business();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    business.subThread(i);
                }
            }
        }).start();

        for (int i = 0; i < 50; i++) {
            business.mainThread(i);
        }
    }


    private class Business {
        boolean isSub = true;

        public synchronized void mainThread(int i) {
            if (isSub) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            for (int j = 0; j < 100; j++) {
                System.out.println(Thread.currentThread().getName() + ":i=" + i + "j=" + j);
            }
            isSub = true;
            this.notify();
        }

        public synchronized void subThread(int i) {
            if (!isSub) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            for (int j = 0; j < 10; j++) {
                System.out.println(Thread.currentThread().getName() + ":i=" + i + "j=" + j);
            }
            isSub = false;
            this.notify();
        }
    }
}
